<template>
   <div class="app-container">
      <div class="p4">
         <FaSearchBar :show-toggle="false">
            <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="80px">
               <el-form-item label="菜单名称" prop="name">
                  <el-input v-model="queryParams.name" placeholder="请输入菜单名称" clearable style="width: 150px"
                     @keyup.enter="handleQuery" />
               </el-form-item>
               <el-form-item label="状态" prop="status">
                  <el-select v-model="queryParams.status" placeholder="菜单状态" clearable style="width: 150px">
                     <el-option v-for="dict in sys_common_status" :key="dict.value" :label="dict.label"
                        :value="dict.value" />
                  </el-select>
               </el-form-item>
               <el-form-item>
                  <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                  <el-button @click="resetQuery">重置</el-button>
               </el-form-item>
            </el-form>
         </FaSearchBar>
         <el-divider border-style="dashed" style="margin:0px 0px 20px 0px" />

         <el-space wrap>
            <el-button type="primary" icon="Plus" @click="handleAdd" v-auth="['system:menu$add']">新增</el-button>

         </el-space>
         <el-table v-loading="loading" :data="menuList" row-key="id" ref="tableRef" lazy :load="loadChildren"
            :tree-props="{ children: 'children', hasChildren: 'hasChildren' }" stripe highlight-current-row border
            class="mt4">
            <el-table-column prop="name" label="菜单名称" :show-overflow-tooltip="true" width="200">
               <template #default="scope">
                  <svg-icon :icon-class="scope.row.icon" style="display: inline;margin-right: 5px;"
                     v-if="scope.row.icon != '' && scope.row.icon != '#'" />{{ scope.row.name }}
               </template>
            </el-table-column>
            <el-table-column prop="status" align="center" label="类型" width="110">
               <template #default="scope">
                  <el-tag type="info" v-if="scope.row.type === 'B'">板块</el-tag>
                  <el-tag type="info" v-if="scope.row.type === 'M'">目录</el-tag>
                  <el-tag type="warning" v-else-if="scope.row.type === 'C'">菜单</el-tag>
                  <el-tag type="success" v-else-if="scope.row.type === 'D'">低代码菜单</el-tag>
                  <el-tag type="danger" v-else-if="scope.row.type === 'F'">按钮</el-tag>
               </template>
            </el-table-column>
            <el-table-column prop="sort" align="center" label="排序" width="60"></el-table-column>
            <el-table-column prop="sign" label="权限标识" :show-overflow-tooltip="true" width="160"></el-table-column>
            <el-table-column prop="path" label="路由地址" :show-overflow-tooltip="true" width="160"></el-table-column>
            <el-table-column prop="component" label="组件路径" :show-overflow-tooltip="true" width="160"></el-table-column>
            <el-table-column prop="visible" align="center" label="显示" width="80">
               <template #default="scope">
                  <DictTag :dictData="sys_visible" :value="scope.row.visible" />
               </template>
            </el-table-column>
            <el-table-column prop="status" align="center" label="状态" width="80">
               <template #default="scope">
                  <DictTag :dictData="sys_common_status" :value="scope.row.status" />
               </template>
            </el-table-column>
            <el-table-column label="创建时间" align="center" width="200" prop="createdAt">
               <template #default="scope">
                  <span>{{ parseTime(scope.row.createdAt) }}</span>
               </template>
            </el-table-column>
            <el-table-column label="" width="260px" class-name="small-padding fixed-width">
               <template #default="scope">
                  <el-button size="small" type="primary" icon="Plus" @click="handleAdd(scope.row)"
                     v-auth="['system:menu$add']">新增
                  </el-button>
                  <el-button size="small" plain type="success" icon="Edit" @click="handleUpdate(scope.row)"
                     v-auth="['system:menu$edit']">修改
                  </el-button>
                  <el-button size="small" plain type="danger" icon="Delete" @click="handleDelete(scope.row)"
                     v-auth="['system:menu$remove']">删除
                  </el-button>
               </template>
            </el-table-column>
         </el-table>
      </div>
      <!-- 添加或修改菜单对话框 -->
      <el-drawer v-model="open" :title="title" :before-close="handleDesignClose" size="30%" append-to-body>
         <el-form ref="menuRef" :model="form" :rules="rules" label-width="100px">
            <el-form-item label="上级菜单">
               <el-tree-select v-model="form.parentId" :data="menuOptions"
                  :props="{ value: 'id', label: 'name', children: 'children' }" value-key="id" placeholder="选择上级菜单"
                  check-strictly />
            </el-form-item>
            <el-form-item label="菜单类型" prop="type">
               <el-radio-group v-model="form.type" @change="changeType">
                  <el-radio-button value="B" label="板块" />
                  <el-radio-button value="M" label="目录" />
                  <el-radio-button value="C" label="菜单" />
                  <el-radio-button value="D" label="低代码菜单" />
                  <el-radio-button value="F" label="按钮" />
               </el-radio-group>
            </el-form-item>
            <el-form-item label="菜单名称" prop="name">
               <el-input v-model="form.name" placeholder="请输入菜单名称" />
            </el-form-item>
            <el-row>
               <el-col :span="12">
                  <el-form-item label="显示排序" prop="sort">
                     <el-input-number v-model="form.sort" controls-position="right" :min="0" />
                  </el-form-item>
               </el-col>
               <el-col :span="12">
                  <el-form-item label="菜单图标" prop="icon" v-if="form.type != 'F'">
                     <el-popover placement="bottom-start" :width="540" v-model:visible="showChooseIcon" trigger="click"
                        @show="showSelectIcon">
                        <template #reference>
                           <el-input v-model="form.icon" placeholder="点击选择图标" @blur="showSelectIcon"
                              v-click-outside="hideSelectIcon" readonly>
                              <template #prefix>
                                 <svg-icon v-if="form.icon" :icon-class="form.icon" class="el-input__icon"
                                    style="height: 32px;width: 16px;" />
                                 <el-icon v-else style="height: 32px;width: 16px;">
                                    <search />
                                 </el-icon>
                              </template>
                           </el-input>
                        </template>
                        <icon-select ref="iconSelectRef" @selected="selected" :active-icon="form.icon" />
                     </el-popover>
                  </el-form-item></el-col>
            </el-row>
            <el-form-item v-if="form.type != 'F' && form.type != 'B' && form.type != 'D'">
               <el-checkbox border :checked="form.isFrame" v-model="form.isFrame">
                  是否外链
                  <el-tooltip content="选择是外链则路由地址需要以`http(s)://`开头" placement="top">
                     <el-icon><question-filled /></el-icon>
                  </el-tooltip>
               </el-checkbox>
            </el-form-item>
            <el-form-item v-if="form.type != 'F' && form.type != 'B'">
               <el-checkbox border :checked="form.redirect" v-model="form.redirect">
                  是否重定向
                  <el-tooltip content="选择重定向，指定的路由地址，路由地址为完整的。如：/user/role" placement="top">
                     <el-icon><question-filled /></el-icon>
                  </el-tooltip>
               </el-checkbox>
            </el-form-item>
            <el-form-item prop="path" v-if="form.type != 'F' && form.type != 'B'">
               <template #label>
                  <span>
                     <el-tooltip content="访问的路由地址，如：`user`，如外网地址需内链访问则以`http(s)://`开头" placement="top">
                        <el-icon><question-filled /></el-icon>
                     </el-tooltip>
                     路由地址
                  </span>
               </template>
               <el-input v-model="form.path" placeholder="请输入路由地址" />
            </el-form-item>
            <el-form-item prop="component" v-if="form.type == 'C' && form.type != 'D' && !form.redirect">
               <template #label>
                  <span>
                     <el-tooltip content="访问的组件路径，如：`system/user/index`，默认在`views`目录下" placement="top">
                        <el-icon><question-filled /></el-icon>
                     </el-tooltip>
                     组件路径
                  </span>
               </template>
               <el-input v-model="form.component" placeholder="请输入组件路径" />
            </el-form-item>
            <el-form-item v-if="form.type != 'M' && form.type != 'B'">
               <el-input v-model="form.sign" placeholder="请输入权限标识" maxlength="100" />
               <template #label>
                  <span>
                     <el-tooltip content="控制器中定义的权限字符，如：@PreAuthorize(`@perm.hasPermission('system:user$list')`)"
                        placement="top">
                        <el-icon><question-filled /></el-icon>
                     </el-tooltip>
                     权限字符
                  </span>
               </template>
            </el-form-item>
            <el-form-item v-if="form.type == 'C' || form.type == 'D'">
               <el-input v-model="form.query" placeholder="请输入路由参数" maxlength="255" />
               <template #label>
                  <span>
                     <el-tooltip content='访问路由的默认传递参数，如：`{"name": "easy"}`' placement="top">
                        <el-icon><question-filled /></el-icon>
                     </el-tooltip>
                     路由参数
                  </span>
               </template>
            </el-form-item>
            <el-form-item prop="activePath" v-if="form.type == 'C' && form.type != 'D' && !form.redirect">
               <template #label>
                  <span>
                     <el-tooltip content="激活地址，如：`uc/user`，激活的菜单会被选中突出标记" placement="top">
                        <el-icon><question-filled /></el-icon>
                     </el-tooltip>
                     激活地址
                  </span>
               </template>
               <el-input v-model="form.activePath" placeholder="请输入激活地址" />
            </el-form-item>
            <el-form-item v-if="form.type == 'C' || form.type == 'D'">
               <el-checkbox border :checked="form.isCache" v-model="form.isCache">
                  是否缓存
                  <el-tooltip content="选择是则会被`keep-alive`缓存，需要匹配组件的`name`和地址保持一致" placement="top">
                     <el-icon><question-filled /></el-icon>
                  </el-tooltip>
               </el-checkbox>
            </el-form-item>
            <el-form-item v-if="form.type != 'F' && form.type != 'B'">
               <el-checkbox border :checked="form.visible" v-model="form.visible">
                  是否可见
                  <el-tooltip content="选择不可见将不会出现在菜单中，但仍然可以访问" placement="top">
                     <el-icon><question-filled /></el-icon>
                  </el-tooltip>
               </el-checkbox>
            </el-form-item>
            <el-form-item v-if="form.type != 'F'">
               <template #label>
                  <span>
                     <el-tooltip content="选择停用则路由将不会出现在菜单中，也不能访问" placement="top">
                        <el-icon><question-filled /></el-icon>
                     </el-tooltip>
                     菜单状态
                  </span>
               </template>
               <el-radio-group v-model="form.status">
                  <el-radio border v-for="dict in sys_common_status" :key="dict.value" :label="Number(dict.value)">{{ dict.label
                     }}</el-radio>
               </el-radio-group>
            </el-form-item>
         </el-form>
         <template #footer>
            <div class="dialog-footer">
               <el-button type="primary" @click="submitForm">确 定</el-button>
               <el-button @click="cancel">取 消</el-button>
            </div>
         </template>
      </el-drawer>
   </div>
</template>

<script setup name="Menu">
import apiMenu from "@/api/system/menu";
import SvgIcon from "@/components/SvgIcon/index.vue";
import IconSelect from "@/components/IconSelect/index.vue";
import { ClickOutside as vClickOutside } from 'element-plus'
import useUserStore from '@/store/modules/user'
const { proxy } = getCurrentInstance();
const userStore = useUserStore();
const { sys_visible, sys_common_status } = proxy.useDict("sys_visible", "sys_common_status");

const menuList = ref([]);
const open = ref(false);
const loading = ref(false);
const title = ref("");
const menuOptions = ref([]);
const showChooseIcon = ref(false);
const iconSelectRef = ref(null);
const tableRef = ref();
const maps = new Map();

const data = reactive({
   form: {},
   queryParams: {
      name: undefined,
      visible: undefined,
      parentId: "0"
   },
   rules: {
      name: [{ required: true, message: "菜单名称不允许为空", trigger: "blur" }],
      sort: [{ required: true, message: "顺序不允许为空", trigger: "blur" }]
   },
});

const { queryParams, form, rules } = toRefs(data);

/** 查询菜单列表 */
function getList() {
   // loading.value = true
   queryParams.value.parentId = "0"
   apiMenu.childrenMenu(queryParams.value).then(response => {
      menuList.value = response.data;
   }).finally(() => {
      loading.value = false
   })
}
/** 查询菜单下拉树结构 */
function getTreeselect() {
   menuOptions.value = [];
   apiMenu.list().then(response => {
      const menu = { id: 0, name: "主板块", children: [] };
      menu.children = proxy.handleTree(response.data, "id");
      menuOptions.value.push(menu);
   });
}
/** 取消按钮 */
function cancel() {
   open.value = false;
   reset();
}
/** 表单重置 */
function reset() {
   form.value = {
      id: undefined,
      parentId: 0,
      name: undefined,
      icon: undefined,
      type: "M",
      sort: 0,
      isFrame: false,
      isCache: true,
      visible: true,
      status: 0,
      redirect: false,
      activePath: "",
   };
   proxy.resetForm("menuRef");
}
/** 展示下拉图标 */
function showSelectIcon() {
   iconSelectRef.value.reset();
   showChooseIcon.value = true;
}
function changeType(val) {
   if (val === 'D') {
      form.value.component = "xcode/biz/index"
   } else {
      form.value.component = undefined
   }
}

/** 选择图标 */
function selected(name) {
   form.value.icon = name;
   showChooseIcon.value = false;
}
/** 图标外层点击隐藏下拉列表 */
function hideSelectIcon(event) {
   var elem = event.relatedTarget || event.srcElement || event.target || event.currentTarget;
   var className = elem.className;
   if (className !== "el-input__inner") {
      showChooseIcon.value = false;
   }
}
/** 搜索按钮操作 */
function handleQuery() {
   getList();
}
/** 重置按钮操作 */
function resetQuery() {
   proxy.resetForm("queryRef");
   handleQuery();
}
/** 新增按钮操作 */
function handleAdd(row) {
   reset();
   getTreeselect();
   if (row != null && row.id) {
      form.value.parentId = row.id;
   } else {
      form.value.parentId = 0;
   }
   open.value = true;
   title.value = "添加菜单";
}
/** 修改按钮操作 */
async function handleUpdate(row) {
   reset();
   await getTreeselect();
   apiMenu.getById(row.id).then(response => {
      if (response.data.parentId === '0') {
         response.data.parentId = null
      }
      form.value = response.data;
      open.value = true;
      title.value = "修改菜单";
   });
}
/** 提交按钮 */
function submitForm() {
   proxy.$refs["menuRef"].validate(valid => {
      if (valid) {
         if (form.value.id != undefined) {
            apiMenu.update(form.value).then(response => {
               proxy.$modal.success("修改成功");
               open.value = false;
               let r = { ...form.value }
               refreshChildren(r.parentId)
            });
         } else {
            apiMenu.add(form.value).then(response => {
               proxy.$modal.success("新增成功");
               open.value = false;
               let r = { ...form.value }
               addNode(tableRef.value.data, r.parentId)
               refreshChildren(r.parentId)
            });
         }
      }
   });
}
/** 删除按钮操作 */
function handleDelete(row) {
   proxy.$modal.confirm('是否确认删除名称为"' + row.name + '"的数据项?').then(function () {
      return apiMenu.delete(row.id);
   }).then(() => {
      deleteNode(menuList.value, row.id)
      proxy.$modal.success("删除成功");
   }).catch(() => { });
}


// 懒加载子节点方法
const loadChildren = async (row, treeNode, resolve) => {
   row.loading = true
   maps.set(row.id, { row, treeNode, resolve })
   apiMenu.childrenMenu({ parentId: row.id }).then(response => {
      updateTree(tableRef.value.data, row.id, response.data)
      resolve(response.data)
   }).catch((error) => {
      console.error('加载失败:', error)
      resolve([])
   }).finally(() => {
      setTimeout(() => row.loading = false, 500)
   })
}

const refreshChildren = (parentId) => {
   if (parentId == '0') {
      getList()
   } else {
      const map = maps.get(parentId);
      if (map) {
         loadChildren(map.row, map.treeNode, map.resolve)
      }
   }
}
const addNode = (data, targetId) => {
   for (let i = 0; i < data.length; i++) {
      if (data[i].id === targetId) {
         data[i].hasChildren = true
         tableRef.value.toggleRowExpansion(data[i], false)
         nextTick(() => {
            tableRef.value.toggleRowExpansion(data[i], true)
         })
      }
      if (data[i].children && data[i].children.length > 0) {
         addNode(data[i].children, targetId);
      }
   }
   return false
}
// 更新完整数据树
const updateTree = (tree, targetId, newChildren) => {
   for (const node of tree) {
      if (node.id === targetId) {
         node.children = newChildren
         return true
      }
      if (node.children) {
         if (updateTree(node.children, targetId, newChildren)) return true
      }
   }
   return false
}

// 执行删除
const deleteNode = (data, targetId) => {
   for (let i = 0; i < data.length; i++) {
      if (data[i].id === targetId) {
         data.splice(i, 1)
         return true
      }
      if (data[i].children && data[i].children.length > 0) {
         if (deleteNode(data[i].children, targetId)) {
            return true
         }
      }
   }
   return false
}

getList();
</script>
